from docx import Document
import os


def replace_text_in_paragraph(paragraph, replacements):
    for run in paragraph.runs:
        for old_text, new_text in replacements.items():
            if old_text in run.text:
                run.text = run.text.replace(old_text, new_text)


def replace_all(text, replacements):
    for old, new in replacements.items():
        text = text.replace(old, new)
    return text


def replace_text_in_table(table, replacements):
    for row_index, row in enumerate(table.rows):
        try:
            # 检查当前行的单元格数量是否符合预期
            if len(row.cells) != len(table.columns):
                print(
                    f"警告: 表格行 {row_index} 的单元格数量({len(row.cells)})与列数({len(table.columns)})不匹配, 跳过该行。")
                continue

            for cell in row.cells:
                # 检查单元格是否包含文本
                if cell.text:
                    # 替换单元格内容
                    new_text = replace_all(cell.text, replacements)
                    cell.text = new_text
        except IndexError:
            print(f"错误: 表格行 {row_index} 的单元格数量与列数不匹配, 无法替换该行内容。")
            continue


def replace_text_in_document(doc, replacements):
    for paragraph in doc.paragraphs:
        replace_text_in_paragraph(paragraph, replacements)
    for table in doc.tables:
        replace_text_in_table(table, replacements)


def fix(input_file, replacements):
    # Check if the file exists
    if not os.path.isfile(input_file):
        raise FileNotFoundError(f"Package not found at '{input_file}'")

    # Load the document
    doc = Document(input_file)

    # Replace text in the document
    replace_text_in_document(doc, replacements)

    # Save the modified document (overwriting the original)
    doc.save(input_file)


if __name__ == "__main__":
    input_file = 'source/技术服务合同-+++++项目.docx'
    replacements = {
        '${项目名称}': '郑州华电富士康综合能源',
        '${小写金额}': '2123.50',
        '${纳税人电话}': '',
        '${客户名称}': '王一然',
        '${交付经理}': '利息也',
        '${省解决方案经理}': '王明阳',
        '${采购经理}': '李清照',
    }

    fix(input_file, replacements)
